package com.anbinh.doctor.fragment.account;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.anbinh.doctor.GcmRegister;
import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.AccountAdapter;
import com.anbinh.doctor.fragment.FragmentLogin;
import com.anbinh.doctor.model.AccountInfo;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.ItemMeu;
import com.anbinh.doctor.model.NewAvatar;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.AccountType;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class FragmentAccount extends Fragment {
	public static FragmentAccount fragment = null;
	private View mView;
	List<ItemMeu> mList;
	private CircleProgressBar loadding;
	private ImageView avatar;
	private UserLogin userLogin;
	private TextView lblName;
	private RatingBar ratingBar1;
	protected TextView chuyenkhoa;
	private IRcallBak calBak;
	public boolean isRefreshAccount = false;
	private ListView mGridView;

	public static FragmentAccount newInstance() {
		if (fragment == null) {
			fragment = new FragmentAccount();
		}
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
		if (activity instanceof IRcallBak) {
			calBak = (IRcallBak) activity;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);

		if (userLogin != null)
			lblName.setText(userLogin.getData().getUserInfo().getFull_name());
		if (isRefreshAccount) {
			onLoadData();
			isRefreshAccount = false;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_message, null);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mGridView = (ListView) mView.findViewById(R.id.listView1);
		View header = getActivity().getLayoutInflater().inflate(
				R.layout.header_account, null);
		ratingBar1 = (RatingBar) header.findViewById(R.id.ratingBar1);

		mGridView.addHeaderView(header);
		loadding = (CircleProgressBar) header.findViewById(R.id.loadding);
		lblName = (TextView) header.findViewById(R.id.lblName);
		chuyenkhoa = (TextView) header.findViewById(R.id.lblChuyenKhoa);
		avatar = (ImageView) header.findViewById(R.id.avatar);
		onLoadData();
		avatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.pickFileImage(getActivity(), Utils.REQ_EDIT_AVATAR);
			}
		});

	}

	public void onLoadData() {
		mList = new ArrayList<ItemMeu>();
		mList = Utils.getMenu(getActivity(), R.menu.account);
		if (userLogin.getData().getUserInfo().getType() != AccountType.PHONGKHAM
				.getCode()) {
			mList.remove(7);
		}

		AccountAdapter adapter = new AccountAdapter(getActivity(),
				R.layout.item_account, mList);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0)
					return;
				onClickItem(position - 1);
			}
		});

		ImageLoader imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()
				.getApplicationContext()));

		Bitmap bmp = imageLoader.loadImageSync(userLogin.getData()
				.getUserInfo().getAvatar());
		if (bmp == null) {

			imageLoader.displayImage(userLogin.getData().getUserInfo()
					.getAvatar(), avatar, Utils.getOptions(getActivity()),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
						}
					});
		} else {
			avatar.setImageBitmap(bmp);
		}

		getAccountInfo();
	}

	public void getAccountInfo() {
		loadding.setVisibility(View.VISIBLE);
		ServerController.getInstance(getActivity()).requestGetAccountInfo(
				userLogin.getData().getToken(), new OnRequest<AccountInfo>() {

					@Override
					public void onSuccess(AccountInfo data) {
						loadding.setVisibility(View.INVISIBLE);
						if (data.getResponsecode() >= 0) {
							ratingBar1.setRating(data.getData().getProfile()
									.getRating());
							chuyenkhoa.setText(data.getData().getProfile()
									.getSpeciality());
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
					}
				});

	}

	public void updateInfo(Intent data) {
		final UserLogin user = Utils.getAccountModel(getActivity(),
				Utils.KEY_USER);

		String token = user.getData().getToken();
		Uri selectedImage = data.getData();
		Bitmap avatarbm = null;
		try {
			avatarbm = Utils.decodeUri(getActivity(), selectedImage, 200);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if (avatarbm != null) {
			avatar.setImageBitmap(avatarbm);
		}
		File file = new File(Utils.getRealPathFromURI(getActivity(),
				selectedImage));
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestUploadAvatar(token,
				file, new OnRequest<NewAvatar>() {

					@Override
					public void onSuccess(NewAvatar data) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						if (data.getResponsecode() >= 0) {
							userLogin.getData().getUserInfo()
									.setAvatar(data.getData().getNewAvatar());
							Utils.updateData(getActivity(), Utils.KEY_USER,
									userLogin);
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						Utils.showMessage(getActivity(), message);
					}
				});
	}

	public void pickFile(Activity activity, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_PICK);

		// TODO Auto-generated method stub
		// call android default gallery
		intent.setType("image/*");
		// ******** code for crop image
		activity.startActivityForResult(intent, requestCode);

	}

	public void onClickItem(int position) {
		int id = mList.get(position).getRegId();
		if (id == R.id.dang_xuat) {
			Bundle bundle = new Bundle();
			bundle.putBoolean(Utils.KEY_UPDATE, false);
			calBak.onDisplay(-1, null);
			onResetDataAccount();
			Utils.updateData(getActivity(), Utils.KEY_USER, null);
			getActivity()
					.getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fragment_container,
							FragmentLogin.newInstance(), "TAG_MAIN")
					.addToBackStack(null).commit();
			onLogout();

			return;
		}

		Bundle bundle = new Bundle();
		bundle.putInt(Utils.KEY, id);
		if (position == 1)
			bundle.putBoolean(Utils.CUSTOMBAR, true);
		else
			bundle.putBoolean(Utils.CUSTOMBAR, false);
		bundle.putString(Utils.TITLE, mList.get(position).getTitle());
		Utils.getNewIntent(getActivity(), bundle);
	}

	private void onLogout() {
		ServerController.getInstance(getActivity()).requestOnLogout(
				userLogin.getData().getToken(), GcmRegister.mGcmId,
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						Utils.showMessage(getActivity(), data.getDescription());
					}

					@Override
					public void onError(int errorCode, String message) {
					}
				});
	}

	public void onResetDataAccount() {

		isRefreshAccount = true;

		/*
		 * FragmentListPatients.newInstance().setRefreshPatient(true);
		 * FragmentMain.newInstance().setRefreshMessage(true);
		 * FragmentMain.newInstance().setRefreshLichkham(true);
		 * FragmentMain.newInstance().setRefreshAppointMent(true);
		 */
	}

}
